<template>
  <div class="course-schedule">
    <FullCalendar ref="fullCalendarRef" :options="calendarOptions" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import FullCalendar from '@fullcalendar/vue3';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import { useCourseStore } from '@/stores/course';
import type { CourseSchedule } from '@/types/course';
import { type CalendarOptions,type CalendarApi,type EventSourceInput } from '@fullcalendar/core';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

dayjs.locale('zh-cn');

const fullCalendarRef = ref(null);
const courseStore = useCourseStore();
const courses = ref<CourseSchedule[] | null>(null);
const calendarApi = ref<CalendarApi | null>(null);

onMounted(async () => {
  try {
    await courseStore.fetchSelectedCourses();
    courses.value = courseStore.selectedCourses;
    nextTick(() => {
      
      calendarApi.value = (fullCalendarRef.value as any)?.getApi();
    
    });
  } catch (error) {
    console.error('Failed to fetch courses:', error);
  }
});

const events = computed(() => {
  if (!courses.value) return [];
  return courses.value.flatMap((course) =>
    course.scheduleInfo.map((schedule) => ({
      id: `${course.id}-${schedule.id}`,
      title: `${course.course.courseName} (${schedule.room})`,
      start: new Date(schedule.startTime as unknown as string),
      end: new Date(schedule.endTime as unknown as string),
      allDay: false,
      extendedProps: {
        room: schedule.room,
        teacher: `${course.teacher.name} (${course.teacher.title})`,
        courseName: course.course.courseName,
        courseId: course.course.courseId
      }
    }))
  );
});

const calendarOptions = ref<CalendarOptions>({
  plugins: [timeGridPlugin, interactionPlugin],
  initialView: 'timeGridWeek',
  selectable: true,
  select: (arg) => {
    console.log('Selected dates:', arg.start, arg.end);
  },
  events: events as EventSourceInput | undefined,
  eventContent: renderEventContent,
  eventClick: (arg) => {
    const index = events.value.findIndex((event) => event.id === arg.event.id);
    if (index !== -1) {
      events.value.splice(index, 1);
      calendarApi.value?.refetchEvents();
    }
  },
  locale: 'zh-cn',
  headerToolbar: {
    left: 'prev,next today',
    center: 'title',
    right: 'timeGridWeek,timeGridDay'
  },
  aspectRatio: 2,
  firstDay: 1,
  slotMinTime: '07:00:00',
  slotMaxTime: '20:00:00'
});

function renderEventContent(eventInfo: { event: { title: string; extendedProps: { room: string; teacher: string } } }) {
  return {
    html: `
      <div class="fc-event-main">
        <strong>${eventInfo.event.title}</strong>
        <div>教室: ${eventInfo.event.extendedProps.room}</div>
        <div>教师: ${eventInfo.event.extendedProps.teacher}</div>
      </div>
    `
  };
}
</script>

<style>
.fc-event-main {
  padding: 5px;
  background-color: #4caf50;
  color: white;
  border: 1px solid #45a049;
  border-radius: 5px;
}
</style>